package edu.isquen.util.json;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class JsonUtil {
	
	public static Collection<Object> toCollection(String JSONStr) {
		Collection<Object> rtn = new ArrayList<Object>();

		JSONArray array = JSONArray.fromObject(JSONStr);
		for (int i = 0; i < array.size(); i++) {
			Object obj = array.get(i);
			if (obj instanceof JSONObject) {
				rtn.add(toMap((JSONObject) obj));
			} else {
				rtn.add(obj);
			}
		}

		return rtn;
	}
	
	public static Map<String, Object> toMap(String jsonStr){
		JSONObject jsonobjec =JSONObject.fromObject(jsonStr);
		return toMap(jsonobjec);
	}
	
	public static Map<String ,Object> toMap(JSONObject jsonobjec){
		Map<String, Object> rtn=new HashMap<String, Object>();
		if(jsonobjec.isNullObject()){
			return null;
		}
		for(Iterator<?> iter=jsonobjec.keys();iter.hasNext();){
			String key = (String)iter.next();
			Object obj = jsonobjec.get(key);
			
			rtn.put(key, obj);
		}
		
		return rtn;
	}
	
	public static String doCollection2Json(Collection<?> cols){
		JsonConfig jsonConfig=new JsonConfig();
		JSONArray jsonArray=JSONArray.fromObject(cols, jsonConfig);
		return jsonArray.toString();
	}
	
	public static String toJson(Object obj) {
		JSONObject jsonObject = JSONObject.fromObject(obj);
		return jsonObject.toString();
	}
	
//	public static void main(String[] arg) throws Exception{
//		UserProcess process=(UserProcess) ProcessFactory.createProcess(UserProcess.class);
//		//Collection<User> userlist=(Collection<User>)process.doList();
//		//System.out.println("String is--->"+userlist.size());
//	}
}
